package com.wofish.web.controller.goods;

import com.fasterxml.jackson.core.type.TypeReference;
import com.wofish.common.annotation.Log;
import com.wofish.common.core.controller.BaseController;
import com.wofish.common.core.domain.AjaxResult;
import com.wofish.common.core.page.TableDataInfo;
import com.wofish.common.enums.BusinessType;
import com.wofish.common.json.JsonUtil;
import com.wofish.common.utils.poi.ExcelUtil;
import com.wofish.goods.domain.*;
import com.wofish.goods.dto.ProductsIndex;
import com.wofish.goods.dto.SpecObject;
import com.wofish.goods.dto.SpecValuesDto;
import com.wofish.goods.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 货品 信息操作处理
 * 
 * @author wofish
 * @date 2019-06-16
 */
@Slf4j
@Controller
@RequestMapping("/goods/products")
public class ProductsController extends BaseController {
    private String prefix = "goods/goods";
	
	@Autowired
	private IProductsService productsService;

	@Autowired
	private ISpecificationService specificationService;

	@Autowired
	private IGoodsSpecIndexService goodsSpecIndexService;

	@Autowired
	private ISpecValuesService specValuesService;

	@Autowired
	private IGoodsService goodsService;

	@RequestMapping("/addProductSku")
	public String  addProductSku(Long typeId, String bn, int store, int price, String storePlace, ModelMap mmap){
		//根据类型id查找规格 和规格值
		List<Specification> specificationList = specificationService.querySpecByTypeId(typeId);
		mmap.put("specificationList", JsonUtil.objToStr(specificationList));
		mmap.put("typeId", typeId);
		mmap.put("goodsId", -1);

		mmap.put("bn",bn);
		mmap.put("store",store);
		mmap.put("price", price);
		mmap.put("storePlace", storePlace);

		return prefix + "/add_product_sku";
	}

	@RequestMapping("/editProductSku")
	public String  editProductSku(Long goodsId, Long typeId, ModelMap mmap){
		//根据类型id查找规格 和规格值
		List<Specification> specificationList = specificationService.querySpecByTypeId(typeId);
		Goods goods = goodsService.selectGoodsById(goodsId);

		//查询哪些规格值给选中
		List<SpecValuesDto> specValuesDtoList = getSpecValueDto(goodsId);
		//根据商品id查询货品列表
		List<Products> productsList = productsService.queryProductByGoodsId(goodsId);

		mmap.put("specificationList", JsonUtil.objToStr(specificationList));
		mmap.put("typeId", typeId);
		mmap.put("goodsId", goodsId);
		mmap.put("goods", goods);
		mmap.put("specValuesDtoList", specValuesDtoList);
		mmap.put("productsList", productsList);

		return prefix + "/edit_product_sku";
	}

	private List<SpecValuesDto> getSpecValueDto(Long goodsId){
		List<SpecValuesDto> list = new ArrayList<>();
		List<SpecValues> specValuesList = specValuesService.querySpecValuesByGoodsId(goodsId);

		log.info("specValuesList:{}",specValuesList.size());

		List<SpecValues> listWithoutDup = new ArrayList<>(new LinkedHashSet<>(specValuesList));
		log.info("listWithoutDup:{}",listWithoutDup.size());
		Long tempId = null;

		SpecValuesDto dto = null;
		for (SpecValues sv : listWithoutDup) {

			if (tempId != null && sv.getSpecId().longValue() == tempId) {
				dto.getArr().add(sv.getSpecValueId());
				dto.getStr().add(sv.getSpecValue());
				dto.getImageIds().add(sv.getImageId());
				dto.getImageUrls().add(sv.getImageUrl());
			} else {
				if (tempId != null && dto != null) {
					list.add(dto);
				}
				tempId = sv.getSpecId();
				dto = new SpecValuesDto();
				dto.setId(sv.getSpecId());
				dto.getArr().add(sv.getSpecValueId());
				dto.getStr().add(sv.getSpecValue());
				dto.getImageIds().add(sv.getImageId());
				dto.getImageUrls().add(sv.getImageUrl());
			}
		}
		if (tempId != null && dto != null) {
			list.add(dto);
		}

		return list;
	}


	/**
	 * 保存货品列表
	 * @param productsJson
	 * @param goodsId
	 * @return
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxResult edit(Long goodsId, String productsJson, String productsIndexJson, Long typeId, String specName) {
		//判断货品号是否重复
		List<Products> productsList = JsonUtil.strToObj(productsJson, new TypeReference<List<Products>>() {
		});

		Set<String> bnSet = new HashSet<>();
		for (Products p : productsList) {
			boolean addResult = bnSet.add(p.getBn());
			if (!addResult) {
				return AjaxResult.error("货号重复 bn:" + p.getBn());
			}
		}

		Map<String, Object> dataMap = new HashMap<String, Object>();
		List<ProductsIndex> productsIndexList = JsonUtil.strToObj(productsIndexJson, new TypeReference<List<ProductsIndex>>() {
		});

		if(goodsId == null){//新增商品，保存货品
			//批量保存货品信息
			productsService.insertBatchProducts(productsList);

			//商品规格值
			for (int i = 0; i < productsList.size(); i++) {
				productsIndexList.get(i).setProductId(productsList.get(i).getProductId());
			}
			Date modify = new Date();
			Set<GoodsSpecIndex> goodsSpecIndexSet = new HashSet<>();
			GoodsSpecIndex model = null;
			for (ProductsIndex productsIndex : productsIndexList) {
				List<SpecObject> specObjects = productsIndex.getSpecJson();
				Long productId = productsIndex.getProductId();
				for (SpecObject specObject : specObjects) {
					model = new GoodsSpecIndex();
					model.setLastModify(modify);
					model.setTypeId(typeId);
					model.setGoodsId(goodsId);
					model.setProductId(productId);
					model.setSpecId(specObject.getSpecId());
					model.setSpecValueId(specObject.getSpecValueId());
					model.setImageId(specObject.getImageId());
					model.setImageUrl(specObject.getImageUrl());
					goodsSpecIndexSet.add(model);
				}
			}
			//批量保存货品和规格的关系
			List<GoodsSpecIndex> goodsSpecIndexList = new ArrayList<>(goodsSpecIndexSet);
			goodsSpecIndexService.insertBatch(goodsSpecIndexList);


		}else {
			List<String> bnList = productsService.queryProductsByBns(productsList, goodsId);
			if (CollectionUtils.isNotEmpty(bnList)) {
				return AjaxResult.error("货号重复 bn:" + bnList.get(0));
			}
            boolean saveResult = productsService.editProductsIndex(productsList, productsIndexList, goodsId, typeId);
            log.info("saveResult:{}",saveResult);
		}
		dataMap.put("productsList", productsList);//货品信息
		dataMap.put("productsIndexList", productsIndexList);
		//生成规格 货品数量
		dataMap.put("num", productsList.size());//货品信息
		dataMap.put("specNames", specName);//货品信息

		return AjaxResult.success(dataMap);

	}

	
	@RequiresPermissions("goods:products:view")
	@GetMapping()
	public String products() {
	    return prefix + "/products";
	}
	
	/**
	 * 查询货品列表
	 */

	@RequiresPermissions("goods:products:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Products products) {
		startPage();
        List<Products> list = productsService.selectProductsList(products);
		return getDataTable(list);
	}
	



	/**
	 * 导出货品列表
	 */
	@RequiresPermissions("goods:products:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Products products) {
		List<Products> list = productsService.selectProductsList(products);
        ExcelUtil<Products> util = new ExcelUtil<Products>(Products.class);
        return util.exportExcel(list, "products");
    }
	
	/**
	 * 新增货品
	 */
	@GetMapping("/add")
	public String add() {
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存货品
	 */
	@RequiresPermissions("goods:products:add")
	@Log(title = "货品", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Products products) {
		return toAjax(productsService.insertProducts(products));
	}

	/**
	 * 修改货品
	 */
	@GetMapping("/edit/{productId}")
	public String edit(@PathVariable("productId") Long productId, ModelMap mmap) {
		Products products = productsService.selectProductsById(productId);
		mmap.put("products", products);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存货品
	 */

//	@RequiresPermissions("goods:products:edit")
//	@Log(title = "货品", businessType = BusinessType.UPDATE)
//	@PostMapping("/edit")
//	@ResponseBody
//	public AjaxResult editSave(Products products) {
//		return toAjax(productsService.updateProducts(products));
//	}
	
	/**
	 * 删除货品
	 */

	@RequiresPermissions("goods:products:remove")
	@Log(title = "货品", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(productsService.deleteProductsByIds(ids));
	}
	
}
